﻿using Nop.Core;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Media;
using Nop.Core.Domain.WindAlert;
using Nop.Services.Helpers;
using Nop.Services.Media;
using Nop.Services.WindAlert;
using Nop.Web.Framework;
using Nop.Web.Models.WindAlert;
using System;
using System.Collections.Generic;
using System.IO;
using System.ServiceModel.Syndication;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;

namespace Nop.Web.Controllers
{
    public partial class WindController : BasePublicController
    {
        #region Fields
        private readonly IWorkContext _workContext;
        private readonly IWindDataService _windDataService;
        private readonly IDateTimeHelper _dateTimeHelper;
        private readonly ISpotService _spotService;
        private readonly IWindHelpers _windHelper;
        private readonly WindAlertSettings _windAlertSettings;
        private readonly IWindAlertPictureService _windAlertPictureService;

        #endregion

        #region Constructors

        public WindController(IWorkContext workContext, IWindDataService windDataService
            , IDateTimeHelper dateTimeHelper
            , ISpotService spotService, IWindHelpers windHelper, WindAlertSettings windAlertSettings,
            IWindAlertPictureService windAlertPictureService)
        {
            this._workContext = workContext;
            this._windDataService = windDataService;
            this._dateTimeHelper = dateTimeHelper;
            this._spotService = spotService;
            this._windHelper = windHelper;
            this._windAlertSettings = windAlertSettings;
            this._windAlertPictureService = windAlertPictureService;
        }

        #endregion

        #region Utilities

        [NonAction]
        protected bool IsCurrentUserRegistered()
        {
            return _workContext.CurrentCustomer.IsRegistered();
        }

       
        #endregion

        public ActionResult Index()
        {
            var model = new IsRegisteredModel() { IsRegistered = true };
            if (!IsCurrentUserRegistered())
                model.IsRegistered = false;
            else
                model.IsRegistered = true;
            model.BlockWindTable = _windAlertSettings.BlockWindTable;
            return View(model);
        }

        public ActionResult Test()
        {
            return View();
        }

        [HttpPost]
        public ActionResult AddForumPicture()
        {
            HttpPostedFileBase uploadedFile = Request.Files["MyFile"];
            bool isUploaded = false;
            string message = "File upload failed";

            int pictureId = 0;
            try
            {
                var forumPicture = new Picture();
                if ((uploadedFile != null) && (!String.IsNullOrEmpty(uploadedFile.FileName)))
                {
                    int pictureMaxSize = _windAlertSettings.PictureMaximumSizeBytes;
                    if (uploadedFile.ContentLength > pictureMaxSize)
                        throw new NopException(string.Format("max size", pictureMaxSize));

                    byte[] commentPictureBinary = uploadedFile.GetPictureBits();
                    forumPicture = _windAlertPictureService.InsertPicture(commentPictureBinary, uploadedFile.ContentType, null, true);
                }
                if (forumPicture != null)
                {
                    pictureId = forumPicture.Id;
                    isUploaded = true;
                    string y = _windAlertPictureService.GetPictureUrl(
                        forumPicture.Id,
                        50,//_mediaSettings.AvatarPictureSize,
                        false, defaultPictureType: PictureType.Entity);
                    string t  = _windAlertPictureService.GetPictureUrl(forumPicture.Id);
                    message = t;
                }
                else

                    message = string.Format("File upload failed: {0}");
            }
            catch (Exception ex)
            {
                message = string.Format("File upload failed: {0}", ex.Message);
            }
            return Json(new { isUploaded = isUploaded, message = message }, "text/html");
        }

        public ActionResult ListRss()
        {
            var feed = new SyndicationFeed(
                                    string.Format("{0}: Stations", "WindAlert"),
                                    "Stations",
                                    new Uri("http://ww.windalert.co.il"),
                                    "StationsRSS",
                                    DateTime.UtcNow);

            var items = new List<SyndicationItem>();
            var stationsItems = _spotService.GetAllSpots(isMetar:false, isStation:true);
            foreach (var s in stationsItems)
            {
                var windStationData = _windDataService.GetWindDataBySpotIdTop1(s.Id);
                var item = new SyndicationItem(s.Name, "", null, String.Format("Station:{0}", s.Id), windStationData.StationAdjustedTime);
                if (windStationData != null)
                {
                    item.ElementExtensions.Add("DateTime", String.Empty, windStationData.StationAdjustedTime.ToString());
                    item.ElementExtensions.Add("WindSpeed", String.Empty, windStationData.WindSpeed.ToString());
                    item.ElementExtensions.Add("WindGust", String.Empty, windStationData.WindGust.ToString());
                    item.ElementExtensions.Add("WindDirection", String.Empty, windStationData.WindDirection.ToString());
                }
                items.Add(item);
            }
            feed.Items = items;
            return new RssActionResult() { Feed = feed };
        }

        public string StationsXml()
        {
            var sb = new StringBuilder();
            var stringWriter = new StringWriter(sb);
            var xmlWriter = new XmlTextWriter(stringWriter);
            xmlWriter.WriteStartDocument();
            xmlWriter.WriteStartElement("WindAlert");
            xmlWriter.WriteAttributeString("Created", DateTime.Now.ToString());

            var stationsItems = _spotService.GetAllSpots(isStation:true, isMetar:false);

            foreach (var s in stationsItems)
            {
                var windStationData = _windDataService.GetWindDataBySpotIdTop1(s.Id);
                xmlWriter.WriteStartElement("Station");

                xmlWriter.WriteElementString("StoreId", null, s.Id.ToString());
                xmlWriter.WriteElementString("Name", null, s.Name);
                xmlWriter.WriteElementString("DateTime", null, windStationData.StationAdjustedTime.ToString());
                xmlWriter.WriteElementString("WindSpeed", null, windStationData.WindSpeed.ToString());
                xmlWriter.WriteElementString("WindGust", null, windStationData.WindGust.ToString());
                xmlWriter.WriteElementString("WindDirection", null, windStationData.WindDirection.ToString());
                xmlWriter.WriteEndElement(); 
            }
            xmlWriter.WriteEndElement();
            xmlWriter.WriteEndDocument();
            xmlWriter.Close();

            Response.ContentType = "text/xml";
            return stringWriter.ToString(); ;
        }

    }
}
